package com.heavenbird.common;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang3.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.heavenbird.common.util.DBUtil;

public class DataSourceListener implements ServletContextListener {
	private static transient Log log = LogFactory.getLog(DataSourceListener.class);
			
	public void contextDestroyed(ServletContextEvent context) {
		if (log.isInfoEnabled()) {
			log.info("DataSourceListener begin to destroy:");
		}
		StopWatch timer = new StopWatch();
		timer.start();
		SessionFactory sessionFactory = DBUtil.getSessionFactory();
		sessionFactory.close();
		timer.stop();
		if (log.isInfoEnabled()) {
			log.info("DataSourceListener has destroyed, cost: " + timer.getTime() + "ms.");
		}
	}

	public void contextInitialized(ServletContextEvent context) {
		if (log.isInfoEnabled()) {
			log.info("DataSourceListener begin to initialize:");
		}
		StopWatch timer = new StopWatch();
		timer.start();
		Configuration cfg = new Configuration().configure("hibernate.cfg.xml");;
		SessionFactory sessionFactory = cfg.buildSessionFactory();
		DBUtil.setSessionFactory(sessionFactory);
		timer.stop();
		if (log.isInfoEnabled()) {
			log.info("DataSourceListener has initialized, cost: " + timer.getTime() + "ms.");
		}
	}

}
